//
//  DrawView.m
//  30205
//
//  Created by student on 16/4/6.
//  Copyright © 2016年 NIIT. All rights reserved.
//

#import "DrawView.h"

@implementation DrawView
-(void)setType:(int)type
{
    _type=type;
    [self setNeedsDisplay];
}
-(void)setList:(NSArray *)list
{
    _list=list;
    [self setNeedsDisplay];
}
-(UIColor *)randomcolor
{
    return [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1];
}
- (void)drawRect:(CGRect)rect
{
    switch (self.type)
    {
        case 0:
        {
             CGPoint center = CGPointMake(rect.size.width/2, rect.size.height/2);
            CGFloat radius=rect.size.width/2*0.8;
            CGFloat startangle=-M_PI_2;
            for(NSDictionary *dict in self.list)
            {
                CGFloat percent=[dict[@"percent"]doubleValue];
                CGFloat endangle=startangle+M_PI *2*percent;
                UIBezierPath *path=[UIBezierPath bezierPath];
                [path moveToPoint:center];
                [path addArcWithCenter:center radius:radius startAngle:startangle endAngle:endangle clockwise:YES];
                [path closePath];
                [[self randomcolor] setFill];
                [path fill];
                NSString *text=dict[@"text"];
                CGFloat x;
                CGFloat y;
                x=center.x+cos(startangle+M_PI*percent)*radius*0.8;
                y=center.y+sin(startangle+M_PI*percent)*radius*0.8;
                CGPoint textpoint=CGPointMake(x, y);
                [[UIColor whiteColor]setStroke];
                [text drawAtPoint:textpoint withAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
                startangle=endangle;
            }
        }
            break;
        case 1:
        {
            CGFloat x,y,w,h;
            w=rect.size.width/(self.list.count*2-1);
            for(int i=0;i<self.list.count;i++)
            {
                NSDictionary *dict=self.list[i];
                x=i*w*2;
                CGFloat percent=[dict[@"percent"] doubleValue];
                h=rect.size.height*percent;
                y=rect.size.height-h;
                UIBezierPath *path=[UIBezierPath bezierPathWithRect:CGRectMake(x, y, w, h)];
                [[self randomcolor] setFill];
                [path fill];
            }
        }
            break;
        default:
            break;
    }
    
}


@end
